#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 版权所有 (c) 2025   保留所有权利。
 * CLR版本：4.0.30319.42000
 * 机器名称：DESKTOP-GLJ2Q8J
 * 公司名称：
 * 命名空间：AutoCAD.EntityTools
 * 唯一标识：6a79b82f-dd3e-4a3d-9890-531f7396cc18
 * 文件名：LengthDimensionOptions
 * 当前用户域：DESKTOP-GLJ2Q8J
 * 
 * 创建者： Guo_79991
 * 电子邮箱：799919859@qq.com
 * 创建时间：2025/9/9 9:40:53
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using static AutoCAD.EntityTools.DimensionOptions;

namespace AutoCAD.EntityTools
{
    /// <summary>
    /// LengthDimensionOptions 的摘要说明
    /// </summary>
    public class DimensionOptions
    {








        /// <summary>
        /// 曲线长度标注选项
        /// </summary>
        public class LengthDimensionOptions
        {
            /// <summary>文字前缀（如：长度、L=等）</summary>
            public string TextPrefix { get; set; } = "";

            /// <summary>文字后缀</summary>
            public string TextSuffix { get; set; } = "";

            /// <summary>文字位置</summary>
            public DimensionTextPosition TextPosition { get; set; } = DimensionTextPosition.Above;

            /// <summary>标注样式名</summary>
            public string DimensionStyle { get; set; } = "Standard";

            /// <summary>基础文字高度</summary>
            public double BaseTextHeight { get; set; } = 2.0;

            /// <summary>基础延伸线长度</summary>
            public double BaseExtensionLength { get; set; } = 1.5;

            /// <summary>箭头大小比例</summary>
            public double ArrowSizeScale { get; set; } = 1.0;
            public int ColorIndex { get; set; } = 3;

            /// <summary>标注偏移距离（相对于曲线）</summary>
            public double OffsetDistance { get; set; } = 10.0;
        }

        /// <summary>
        /// 标注文字位置
        /// </summary>
        public enum DimensionTextPosition
        {
            Above,      // 标注线上方
            Centered,   // 标注线中间
            Below,      // 标注线下方
            PrefixOnly, // 只有前缀（无数值）
            None        // 无文字
        }

        /// <summary>
        /// 标注点位置结构（替代元组）
        /// </summary>
        public struct DimensionPoints
        {
            public Point3d StartPoint { get; set; }
            public Point3d EndPoint { get; set; }
            public Point3d DimensionLinePoint { get; set; }

            public DimensionPoints(Point3d startPoint, Point3d endPoint, Point3d dimensionLinePoint)
            {
                StartPoint = startPoint;
                EndPoint = endPoint;
                DimensionLinePoint = dimensionLinePoint;
            }
        }




    }


    /// <summary>
    /// 长度标注工具类
    /// </summary>
    public static class DimensionTools
    {
        /// <summary>
        /// 在曲线上创建建筑样式长度标注
        /// </summary>
        /// <param name="curve">曲线</param>
        /// <param name="db">database</param>
        /// <param name="options">曲线长度标注选项</param>
        /// <returns>返回</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static AlignedDimension CreateLengthDimension(this Curve curve,Database db,
            LengthDimensionOptions options = null)
        {
            if (curve == null)
                throw new ArgumentNullException(nameof(curve));

            options ??= new LengthDimensionOptions();

            double length = curve.GetLength();

            // 计算比例因子
            double scaleFactor = CalculateScaleFactor(length);

            // 获取标注点位置
            DimensionPoints dimensionPoints = GetDimensionPoints(curve, length, options.OffsetDistance, scaleFactor);

            // 创建标注
            AlignedDimension dimension = CreateAlignedDimension(
                dimensionPoints,
                length,
                options,
                scaleFactor,db
            );

            return dimension;
        }

        /// <summary>
        /// 计算比例因子（基于曲线长度）
        /// </summary>
        private static double CalculateScaleFactor(double length)
        {
            // 根据长度动态调整比例
            if (length < 100) return 1.0;
            if (length < 500) return 1.2;
            if (length < 1000) return 1.5;
            return 2.0;
        }

        /// <summary>
        /// 获取标注点位置
        /// </summary>
        private static DimensionPoints GetDimensionPoints(Curve curve, double length, double offsetDistance, double scaleFactor)
        {
            // 获取曲线的起点和终点
            Point3d startPoint = curve.StartPoint;
            Point3d endPoint = curve.EndPoint;

            // 计算曲线的方向向量
            Vector3d direction = (endPoint - startPoint).GetNormal();

            // 计算垂直偏移方向
            Vector3d offsetDirection = new Vector3d(-direction.Y, direction.X, 0).GetNormal();

            // 计算标注线位置（考虑比例因子）
            double actualOffset = offsetDistance * scaleFactor;
            Point3d dimensionLinePoint = startPoint + offsetDirection * actualOffset;

            // 计算延伸线端点
            Point3d dimStartPoint = startPoint + offsetDirection * (actualOffset * 0.3);
            Point3d dimEndPoint = endPoint + offsetDirection * (actualOffset * 0.3);

            return new DimensionPoints(dimStartPoint, dimEndPoint, dimensionLinePoint);
        }

        /// <summary>
        /// 创建对齐标注
        /// </summary>
        private static AlignedDimension CreateAlignedDimension(
            DimensionPoints points, double length, LengthDimensionOptions options, double scaleFactor, 
            Database db)
        {
            AlignedDimension dimension = new AlignedDimension();

            // 设置标注几何属性
            dimension.XLine1Point = points.StartPoint;
            dimension.XLine2Point = points.EndPoint;
            dimension.DimLinePoint = points.DimensionLinePoint;

            // 计算动态尺寸
            double textHeight = options.BaseTextHeight * scaleFactor;
            double extensionLength = options.BaseExtensionLength * scaleFactor;
            double arrowSize = 0.18 * textHeight * options.ArrowSizeScale;

            // 设置标注样式（使用ObjectId）
            SetDimensionStyle(dimension, options.DimensionStyle,db);

            // 设置文字属性
            dimension.Dimtxt = textHeight;

            // 设置延伸线
            dimension.Dimexo = extensionLength * 0.5;  // 延伸线偏移
            dimension.Dimexe = extensionLength;        // 延伸线长度

            // 设置箭头（建筑标记）
            SetArrowBlocks(dimension, "Architectural Tick" , db);
            dimension.Dimasz = arrowSize;              // 箭头大小

            //设置颜色
            dimension.ColorIndex = options.ColorIndex; 

            // 设置文字内容
            SetDimensionText(dimension, length, options);

            // 设置文字位置
            SetTextPosition(dimension, options.TextPosition);

            // 设置其他属性
            dimension.Dimtad = 1;      // 文字在标注线上方
            dimension.Dimgap = textHeight * 0.5;  // 文字与标注线的间隙

            return dimension;
        }

        /// <summary>
        /// 设置标注样式
        /// </summary>
        private static void SetDimensionStyle(AlignedDimension dimension, string styleName , Database db)
        {
            try
            {
                //Database db = dimension.Database;
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    DimStyleTable dimStyleTable = tr.GetObject(db.DimStyleTableId, OpenMode.ForRead) as DimStyleTable;

                    if (dimStyleTable.Has(styleName))
                    {
                        dimension.DimensionStyle = dimStyleTable[styleName];
                    }
                    tr.Commit();
                }
            }
            catch
            {
                // 如果样式设置失败，使用默认样式
            }
        }

        /// <summary>
        /// 设置箭头块
        /// </summary>
        private static void SetArrowBlocks(AlignedDimension dimension, string blockName , Database db)
        {
            try
            {
                //Database db = dimension.Database;
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    // 检查箭头块是否存在
                    BlockTable blockTable = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                    if (blockTable.Has(blockName))
                    {
                        dimension.Dimblk = blockTable[blockName];
                        dimension.Dimblk1 = blockTable[blockName];
                        dimension.Dimblk2 = blockTable[blockName];
                    }
                    tr.Commit();
                }
            }
            catch
            {
                // 如果箭头块设置失败，使用默认箭头
            }
        }

        /// <summary>
        /// 设置标注文字
        /// </summary>
        private static void SetDimensionText(AlignedDimension dimension, double length, LengthDimensionOptions options)
        {
            string text = FormatDimensionText(length, options);

            // 使用 DimensionText 属性设置文字
            dimension.DimensionText = text;
        }

        /// <summary>
        /// 格式化标注文字
        /// </summary>
        private static string FormatDimensionText(double length, LengthDimensionOptions options)
        {
            if (options.TextPosition == DimensionTextPosition.PrefixOnly)
                return options.TextPrefix;

            if (options.TextPosition == DimensionTextPosition.None)
                return "";

            string lengthText = length.ToString("F0");

            return $"{options.TextPrefix}{lengthText}{options.TextSuffix}";
        }

        /// <summary>
        /// 设置文字位置
        /// </summary>
        private static void SetTextPosition(AlignedDimension dimension, DimensionTextPosition position)
        {
            // 使用 AutoCAD 的标注系统变量来控制文字位置
            switch (position)
            {
                case DimensionTextPosition.Above:
                    dimension.Dimtad = 1;  // 文字在标注线上方
                    break;
                case DimensionTextPosition.Centered:
                    dimension.Dimtad = 0;  // 文字在标注线中间
                    break;
                case DimensionTextPosition.Below:
                    dimension.Dimtad = 4;  // 文字在标注线下方
                    break;
                case DimensionTextPosition.PrefixOnly:
                case DimensionTextPosition.None:
                    dimension.Dimtad = 1;
                    break;
            }
        }

        /// <summary>
        /// 确保建筑标记箭头块存在
        /// </summary>
        public static void EnsureArchitecturalTickBlock(Database db)
        {
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable blockTable = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                if (!blockTable.Has("Architectural Tick"))
                {
                    blockTable.UpgradeOpen();

                    // 创建建筑标记箭头块
                    BlockTableRecord blockRecord = new BlockTableRecord();
                    blockRecord.Name = "Architectural Tick";

                    // 这里可以添加建筑标记的几何图形
                    // 简单创建一个斜线作为标记
                    Line tickLine = new Line(new Point3d(0, 0, 0), new Point3d(1, 1, 0));
                    blockRecord.AppendEntity(tickLine);

                    blockTable.Add(blockRecord);
                    tr.AddNewlyCreatedDBObject(blockRecord, true);
                }

                tr.Commit();
            }
        }
    }








    /// <summary>
    /// 曲线扩展方法
    /// </summary>
    public static class CurveExtensions
    {
        /// <summary>
        /// 安全地计算曲线长度
        /// </summary>
        //public static double GetLength(this Curve curve)
        //{
        //    if (curve == null)
        //        throw new ArgumentNullException(nameof(curve));

        //    try
        //    {
        //        return curve.GetDistanceAtParameter(curve.EndParam);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new InvalidOperationException("计算曲线长度时发生错误", ex);
        //    }
        //}
    }

}